package me.gerry.locktest.manager;

import android.app.KeyguardManager;
import android.app.KeyguardManager.KeyguardLock;
import android.content.Context;
import android.os.Build;

import java.lang.reflect.Method;

public class KeyGuardLocker {
	private String KeyGuardName = "91zns_keyguardlocker";
	private KeyguardManager mKeyguardManager;
	private KeyguardLock _KeyguardLock = null;
	private static KeyGuardLocker keyGuardLocker;
	
	public static KeyGuardLocker getInstance(Context c){
		if(keyGuardLocker == null){
			keyGuardLocker = new KeyGuardLocker(c);
		}
		return keyGuardLocker;
	}

	private KeyGuardLocker(Context c) {
		mKeyguardManager = (KeyguardManager) c
				.getSystemService(Context.KEYGUARD_SERVICE);
	}
	
	public boolean inKeyguardRestrictedInputMode(){
		boolean result = mKeyguardManager.inKeyguardRestrictedInputMode();
		return result;
	}
	
	public synchronized void reenableKeyguard() {
		if (isDisablekeyguard){
			getKeyguardLock().reenableKeyguard();
			isDisablekeyguard = false;
		}
	}

	private boolean isDisablekeyguard = false;
	public synchronized void disableKeyGuard() {
		if (!isDisablekeyguard){
			getKeyguardLock().disableKeyguard();
			isDisablekeyguard = true;
		}
		
	}
	
	private KeyguardLock getKeyguardLock() {
		if (_KeyguardLock == null) {
			_KeyguardLock = mKeyguardManager.newKeyguardLock(KeyGuardName+System.currentTimeMillis());
		}
		return _KeyguardLock;
	}

	/**
	 * 是否有系统密码
	 * @return
     */
	public boolean isKeyguardSecure(Context ctx){
		boolean isAndroidSystemPwd = false;
		try {
			//TODO QA帮忙检查一遍到底是sdk多少有系统密码的时候会黑屏一下。
			if(Build.VERSION.SDK_INT >= 16){
				isAndroidSystemPwd = mKeyguardManager.isKeyguardSecure();
			}else{
				isAndroidSystemPwd = isSecured(ctx);
			}
		}catch (SecurityException e) {
			e.printStackTrace();
		}catch (Exception e) {
			e.printStackTrace();
		}catch (NoSuchMethodError e) {
			e.printStackTrace();
		}
		return isAndroidSystemPwd;
	}

	private boolean isSecured(Context ctx){
		boolean isSecured = false;
		String classPath = "com.android.internal.widget.LockPatternUtils";
		try{
			Class<?> lockPatternClass = Class.forName(classPath);
			Object lockPatternObject = lockPatternClass.getConstructor(Context.class).newInstance(ctx.getApplicationContext());
			Method method = lockPatternClass.getMethod("isSecure");
			isSecured = (boolean) method.invoke(lockPatternObject);
		}catch (Exception e){
			isSecured = false;
		}
		return isSecured;
	}
}
